import React, { useEffect, useState } from 'react';

import { connect, Dispatch } from 'umi';
import { ConnectState } from '@/models/connect';
import { Card, Input, Tag, Tree, Empty } from 'antd';

import { debounce } from 'lodash';

interface JurisdictionProps {
  dispatch: Dispatch;
  selectJurisdiction: (value: any, alltreeData: Array<any>) => void;
  RoleAllList: Array<any>;
  userRole: Array<any>;
  userId: number;
}

const JurisdictionRight: React.FC<JurisdictionProps> = (props) => {
  const { dispatch, selectJurisdiction, RoleAllList, userRole,userId } = props;
  const [expandedKeys, setExpandedKeys] = useState<Array<any>>([]); // 展开指定的树节点
  const [searchValue, setSearchValue] = useState<string>(''); // 搜索关键词
  const [filterTreeData, setFilterTreeData] = useState<Array<any>>([]); // 关键词过滤后的树形结构数据
  const [roleKeys, setRoleKeys] = useState<Array<string>>([]); // 勾选的角色

  const alltreeData: Array<any> = [] // 全部树形数据集合

  // 转换数据为 树形结构数据
  let treeData: Array<any> = [];
  RoleAllList.map((roleitem) => {
    // 获取子级数据
    function getChildrenData(data: Array<any>, parentId: string) {
      let arr: Array<any> = [];
      data.map((v: any) => {
        if (v.parentId == parentId) {
          alltreeData.push({
            title: v.name,
            key: `${roleitem.id}-${v.id}`,
            data: {dataroleId: roleitem.id, values: [v]},
          })

          arr.push({
            title: v.name,
            key: `${roleitem.id}-${v.id}`,
            children: getChildrenData(roleitem.dataRoleDetails, v.id)
          });
        }
      });
      return arr;
    }
    let roleChildrenArr: Array<any> = [];


    roleitem.dataRoleDetails.map((item: any) => {
      if (!item.parentId) {
        alltreeData.push({
          title: item.name,
          key: `${roleitem.id}-${item.id}`,
          data: {dataroleId: roleitem.id, values: [item]},
        })


        roleChildrenArr.push({
          title: item.name,
          key: `${roleitem.id}-${item.id}`,
          children: getChildrenData(roleitem.dataRoleDetails, item.id)
        });
      }
    });

    alltreeData.push({
      title: roleitem.name,
      key: String(roleitem.id),
      data: {dataroleId: roleitem.id, values: roleitem.dataRoleDetails},
    })

    treeData.push({
      title: roleitem.name,
      key: String(roleitem.id),
      children: roleChildrenArr,
    });
  });


  // 搜索框输入值变化
  const onSearchChange = (e: any) => {
    e.persist();
    serach(e.target.value);
  };

  // 展开搜索到的内容节点
  const serach = debounce((value: string) => {
    setSearchValue(value);

    if (value) {
      treeData.map((item) => {
        if (item.children) {
          item.children = item.children.filter((v: any) => v.title.indexOf(value) > -1);
        }
        return item;
      });
      const filterArr = treeData.filter((v: any) => v.children.length);
      let expandedArr: Array<string> = [];
      filterArr.map((item: any) => {
        expandedArr.push(item.key);
      });
      setExpandedKeys(expandedArr);
      setFilterTreeData(filterArr);
    }
  }, 1000);

  // 校验是否包含子节点
  const checkedValFilter = (l_pos: string, checkedNodesPositions: any) => {
    const checks = checkedNodesPositions.filter(
      ({ pos }: any) => l_pos.indexOf(`${pos}-`) == 0 && l_pos != pos,
    );
    return checks.length == 0;
  };

  // 树的选中
  const onCheck = (checkedKeys: any, { checkedNodesPositions }: any) => {
    const rootNodesPositions = checkedNodesPositions.filter(({ pos }) =>
      checkedValFilter(pos, checkedNodesPositions),
    );
    const arr = rootNodesPositions.map((v: any) => v.node.key)
    setRoleKeys(arr)
    selectJurisdiction(arr, alltreeData)
  };

  // 删除选中角色
  const onClose = (key: any) => {
    let arr = roleKeys.map((v) => v);
    arr = arr.filter((v) => v !== key)

    setRoleKeys(arr);
    selectJurisdiction(arr, alltreeData)
  };

  useEffect(() => {
    if (RoleAllList.length == 0) {
      dispatch({
        type: 'dataRole/fetchRoleAllList',
      });
    }
  }, []);
  useEffect(() => {
    // 获取默认值
    if(userRole.length && roleKeys.length === 0) {
      let selectArr: Array<string> = []
      userRole.map(item => {
        if(item.values === '.*') {
          selectArr.push(String(item.dataroleId))
        } else {
          const valuesArr = item.values.split(',')
          valuesArr.map((v:string) => {
            selectArr.push(`${item.dataroleId}-${v}`)
          })
        }
      })
      setRoleKeys(selectArr)
      selectJurisdiction(selectArr, alltreeData)
    }
  }, [userId]);


  return (
    <div style={{ display: 'flex' }}>
      <Card
        title={<Input placeholder="搜索角色" size="small" onChange={onSearchChange} allowClear />}
        style={{ width: 300, marginRight: 20, maxHeight: 500, overflowY: 'auto' }}
        size="small"
      >
        <Tree
          checkedKeys={roleKeys}
          checkable
          onCheck={onCheck}
          onExpand={setExpandedKeys}
          expandedKeys={expandedKeys}
          treeData={searchValue ? filterTreeData : treeData}
        />
        {searchValue && filterTreeData.length === 0 && (
          <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="无搜索结果" />
        )}
      </Card>
      <Card title="已选择" style={{ flex: 1 }} size="small">
        {roleKeys.map((key) => {
          const data = alltreeData.filter((tree) => tree.key === key)[0];
          if (!data) {
            return;
          }
          return (
            <Tag color="green" key={key} closable onClose={() => onClose(key)}>
              {data.title}
            </Tag>
          );
        })}
        {roleKeys.length === 0 ? <Empty description="暂无选择角色" /> : ''}
      </Card>
    </div>
  );
};

export default connect(({ userManage, dataRole }: ConnectState) => ({
  RoleAllList: dataRole.RoleAllList || [],
  userRole: dataRole.userRole || [],
}))(JurisdictionRight);
